package com.tencreat.mall.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tencreat.common.annotation.Log;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.controller.BaseController;
import com.tencreat.common.core.domain.AjaxResult;
import com.tencreat.common.core.domain.entity.SysUser;
import com.tencreat.common.core.domain.model.ReqIdParam;
import com.tencreat.common.core.domain.model.ReqIdsParam;
import com.tencreat.common.enums.BusinessType;
import com.tencreat.common.utils.StringUtils;
import com.tencreat.common.utils.poi.ExcelUtil;
import com.tencreat.domain.account.MallStore;
import com.tencreat.domain.account.MallSupplier;
import com.tencreat.domain.mall.MallComment;
import com.tencreat.domain.mall.MallGoods;
import com.tencreat.domain.mall.dto.MallCommentRequDTO;
import com.tencreat.domain.mall.dto.MallCommentDTO;
import com.tencreat.domain.mall.vo.MallCommentVO;
import com.tencreat.service.account.IMallStoreService;
import com.tencreat.service.account.IMallSupplierService;
import com.tencreat.service.account.IMallUserService;
import com.tencreat.service.mall.IMallCommentService;
import com.tencreat.service.mall.IMallGoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 评论Controller
 *
 * @author tencreat
 * @date 2021-08-15
 */
@Api(tags = "评论api")
@RestController
@RequestMapping("/mall/comment")
public class AdminMallCommentController extends BaseController {
    @Autowired
    private IMallCommentService mallCommentService;

    @Autowired
    private IMallUserService userService;

    @Autowired
    private IMallGoodsService goodsService;

    @Autowired
    private IMallSupplierService mallSupplierService;

    @Autowired
    private IMallStoreService mallStoreService;

    /**
     * 查询评论列表
     */
    @ApiOperation(value = "查询评论列表")
    @PreAuthorize("@ss.hasPermi('mall:comment:list')")
    @PostMapping("/list")
    public HttpResult<IPage<MallCommentVO>> list(@RequestBody MallCommentRequDTO mallCommentRequVo) {
        SysUser user = getLoginCheck().getUser();
        if (user.getUserId() != 1L && user.getUserId() != 2L && StringUtils.isEmpty(mallCommentRequVo.getUsername())) {
            mallCommentRequVo.setUserId(user.getUserId());
        }
        LambdaQueryWrapper<MallComment> wrapper = new LambdaQueryWrapper<>();
        if (mallCommentRequVo.getUuid() != null) {
            wrapper.eq(MallComment::getUuid, mallCommentRequVo.getUuid());
        }
        if (StringUtils.isNotEmpty(mallCommentRequVo.getPhone())) {
            wrapper.eq(MallComment::getPhone, mallCommentRequVo.getPhone());
        }
        if (mallCommentRequVo.getStar() != null) {
            wrapper.eq(MallComment::getStar, mallCommentRequVo.getStar());
        }
        if (mallCommentRequVo.getCommentState() != null) {
            wrapper.eq(MallComment::getCommentState, mallCommentRequVo.getCommentState());
        }
        if (mallCommentRequVo.getStartTime() != null) {
            wrapper.gt(MallComment::getCreateTime, mallCommentRequVo.getStartTime().toLocalDate());
            wrapper.lt(MallComment::getCreateTime, mallCommentRequVo.getEndTime().toLocalDate());
        }
        if (mallCommentRequVo.getGoodsId() != null) {
            wrapper.eq(MallComment::getGoodsId, mallCommentRequVo.getGoodsId());
        }
        if (mallCommentRequVo.getType() != null) {
            wrapper.eq(MallComment::getType, mallCommentRequVo.getType());
        }
        if (mallCommentRequVo.getUsername() != null) {
            MallSupplier mallSupplier = mallSupplierService.lambdaQuery().select(MallSupplier::getUserId, MallSupplier::getId).eq(MallSupplier::getUsername, mallCommentRequVo.getUsername()).one();
            MallStore mallStore = mallStoreService.lambdaQuery().select(MallStore::getUserId, MallStore::getId).eq(MallStore::getStoreName, mallCommentRequVo.getUsername()).one();
            if (null != mallSupplier) {
                List<MallGoods> list2 = goodsService.lambdaQuery().eq(MallGoods::getUserId, mallSupplier.getUserId()).list();
                if (list2.size() < 1) {
                    return HttpResult.ok(new Page<MallCommentVO>(mallCommentRequVo.getPageNum(), mallCommentRequVo.getPageSize()));
                }
                List<Long> goodsList = list2.stream().map(MallGoods::getId).collect(Collectors.toList());
                wrapper.in(MallComment::getGoodsId, goodsList);
            } else if (null != mallStore) {
                List<MallGoods> list2 = goodsService.lambdaQuery().eq(MallGoods::getUserId, mallStore.getUserId()).list();
                if (list2.size() < 1) {
                    return HttpResult.ok(new Page<MallCommentVO>(mallCommentRequVo.getPageNum(), mallCommentRequVo.getPageSize()));
                }
                List<Long> goodsList = list2.stream().map(MallGoods::getId).collect(Collectors.toList());
                wrapper.in(MallComment::getGoodsId, goodsList);
            } else {
                return HttpResult.ok(new Page<MallCommentVO>(mallCommentRequVo.getPageNum(), mallCommentRequVo.getPageSize()));
            }
        }
        //如果后台用户id不为空
        if (mallCommentRequVo.getUserId() != null) {
            //找到对应供应商
            MallSupplier mallSupplier = mallSupplierService.lambdaQuery().eq(MallSupplier::getUserId, mallCommentRequVo.getUserId()).one();
            //找到对应店铺
            MallStore mallStore = mallStoreService.lambdaQuery().eq(MallStore::getUserId, mallCommentRequVo.getUserId()).one();

            List<MallGoods> list2 = goodsService.lambdaQuery().eq(MallGoods::getUserId, mallCommentRequVo.getUserId()).list();
            if (list2.size() < 1) {
                return HttpResult.ok(new Page<MallCommentVO>(mallCommentRequVo.getPageNum(), mallCommentRequVo.getPageSize()));
            }
            List<Long> goodsList = list2.stream().map(MallGoods::getId).collect(Collectors.toList());
            wrapper.in(MallComment::getGoodsId, goodsList);
        }


        if (mallCommentRequVo.getOrderSn() != null) {
            wrapper.eq(MallComment::getOrderSn, mallCommentRequVo.getOrderSn());
        }
        if (mallCommentRequVo.getIsHide() != null) {
            wrapper.eq(MallComment::getIsHide, mallCommentRequVo.getIsHide());
        }
        if (StringUtils.isNotEmpty(mallCommentRequVo.getGoodsName())) {
            List<MallGoods> list = goodsService.lambdaQuery().like(MallGoods::getName, mallCommentRequVo.getGoodsName()).list();
            if (list.size() < 1) {
                return HttpResult.ok(new Page<MallCommentVO>(mallCommentRequVo.getPageNum(), mallCommentRequVo.getPageSize()));
            }
            List<Long> idList = list.stream().map(MallGoods::getId).collect(Collectors.toList());
            wrapper.in(MallComment::getGoodsId, idList);
        }
        wrapper.orderByDesc(MallComment::getCreateTime);
        Page<MallComment> page = new Page<>(mallCommentRequVo.getPageNum(), mallCommentRequVo.getPageSize());
        IPage<MallCommentVO> convert = mallCommentService.page(page, wrapper).convert(this::caseVo);
        return HttpResult.ok(convert);
    }

    private MallCommentVO caseVo(MallComment item) {
        MallCommentVO mallCommentRespVo = new MallCommentVO();
        BeanUtils.copyProperties(item, mallCommentRespVo);
        if (mallCommentRespVo.getGoodsId() != null) {
            MallGoods mallGoods = goodsService.getById(mallCommentRespVo.getGoodsId());
            mallCommentRespVo.setGoodsUrl(mallGoods == null ? null : mallGoods.getPicUrl());
            mallCommentRespVo.setGoodsName(mallGoods == null ? null : mallGoods.getName());
            if (mallGoods != null) {
                MallSupplier mallSupplier = mallSupplierService.lambdaQuery().eq(MallSupplier::getUserId, mallGoods.getUserId()).one();
                mallCommentRespVo.setSupplierName(mallSupplier == null ? null : mallSupplier.getUsername());
                mallCommentRespVo.setMobile(mallSupplier == null ? null : mallSupplier.getMobile());

                MallStore mallStore = mallStoreService.lambdaQuery().eq(MallStore::getUserId, mallGoods.getUserId()).one();
                mallCommentRespVo.setSupplierName(mallStore == null ? null : mallStore.getUsername());
                mallCommentRespVo.setMobile(mallStore == null ? null : mallStore.getMobile());

            }
        }
        if (StringUtils.isNotEmpty(item.getPicUrls())) {
            mallCommentRespVo.setPicUrls(Arrays.asList(item.getPicUrls().split(",")));
        }
        if (StringUtils.isNotEmpty(item.getAdminPicUrls())) {
            mallCommentRespVo.setAdminPicUrls(Arrays.asList(item.getAdminPicUrls().split(",")));
        }
        return mallCommentRespVo;
    }

    /**
     * 导出评论列表
     */
    @ApiOperation(value = "导出评论列表")
    @PreAuthorize("@ss.hasPermi('mall:comment:export')")
    @Log(title = "订单管理>订单评价", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(MallComment mallComment) {
        List<MallComment> list = mallCommentService.selectMallCommentList(mallComment);
        ExcelUtil<MallComment> util = new ExcelUtil<MallComment>(MallComment.class);
        return util.exportExcel(list, "comment");
    }

    /**
     * 获取评论详细信息
     */
    @ApiOperation(value = "获取评论详细信息")
//    @PreAuthorize("@ss.hasPermi('mall:comment:query')")
    @PostMapping(value = "/getInfo")
    public HttpResult<MallCommentVO> getInfo(@RequestBody ReqIdParam id) {
        MallComment mallComment = mallCommentService.selectMallCommentById(id);
        return HttpResult.ok(caseVo(mallComment));
    }


    /**
     * 新增评论
     */
    @ApiOperation(value = "新增评论")
//    @PreAuthorize("@ss.hasPermi('mall:comment:add')")
    @Log(title = "订单管理>订单评价", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public HttpResult<Boolean> add(@RequestBody MallCommentDTO mallCommentVO) {
        return to(mallCommentService.insertMallComment(mallCommentVO));
    }

    /**
     * 修改评论
     */
    @ApiOperation(value = "修改评论")
//    @PreAuthorize("@ss.hasPermi('mall:comment:edit')")
    @Log(title = "订单管理>订单评价", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public HttpResult<Boolean> edit(@RequestBody MallComment mallComment) {
        return to(mallCommentService.updateMallComment(mallComment));
    }

    /**
     * 修改评论
     */
    @ApiOperation(value = "修改评论")
//    @PreAuthorize("@ss.hasPermi('mall:comment:edit')")
    @Log(title = "订单管理>订单评价", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/editComment")
    public HttpResult<Boolean> editComment(@RequestBody MallComment mallComment) {
        return to(mallCommentService.updateMallComment(mallComment));
    }

    /**
     * 删除评论
     */
    @ApiOperation(value = "删除评论")
    @PreAuthorize("@ss.hasPermi('mall:comment:remove')")
    @Log(title = "订单管理>订单评价", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public HttpResult<Boolean> remove(@RequestBody ReqIdsParam ids) {
        return to(mallCommentService.deleteMallCommentByIds(ids));
    }
}
